package com.happy.sky.arithmetic;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.zip.CRC32;

/**
 * @name: MemoryMapTest <tb>
 * @title: 请输入类描述  <tb>
 * @author: cuixinfu@51play.com <tb>
 * @date: 2021/9/8 9:20:05 <tb>
 */
public class MemoryMapTest
{

    public static long checksumMappedFile(Path filename) throws IOException
    {
        //直接通过传入的Path打开文件通道
        try (FileChannel channel = FileChannel.open(filename))
        {
            CRC32 crc = new CRC32();
            int length = (int) channel.size();
            //通过通道的map方法映射内存
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);

            for (int p = 0; p < length; p++)
            {
                int c = buffer.get(p);
                crc.update(c);
            }
            return crc.getValue();
        }
    }

    public static void main(String[] args) throws IOException
    {
        System.out.println("Mapped File:");
        Long start = System.currentTimeMillis();
        Path filename = null ;//new Path("");
        Long crcValue = checksumMappedFile(filename);
        Long end = System.currentTimeMillis();
        System.out.println(Long.toHexString(crcValue));
        System.out.println((end - start) + " milliseconds");
    }
}